package com.smarthealthring.mm.ui.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatImageView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.smarthealthring.mm.R;
import com.smarthealthring.mm.api.ApiRequest;
import com.smarthealthring.mm.base.BaseActivity;
import com.smarthealthring.mm.base.IPresenter;
import com.smarthealthring.mm.bean.UpdateInfoRes;
import com.smarthealthring.mm.contract.PersonalContract;
import com.smarthealthring.mm.event.FinishHomeEvent;
import com.smarthealthring.mm.presenter.LoginPresenter;
import com.smarthealthring.mm.presenter.PersonalPresenter;
import com.smarthealthring.mm.utils.Base64Util;
import com.smarthealthring.mm.utils.BitmapUtils;
import com.smarthealthring.mm.utils.ComToolBar;
import com.smarthealthring.mm.utils.ErrorHanding;
import com.smarthealthring.mm.utils.GlideApp;
import com.smarthealthring.mm.utils.RandomUtil;
import com.smarthealthring.mm.utils.RxBus;
import com.smarthealthring.mm.utils.SPUtils;
import com.smarthealthring.mm.utils.ToastUtil;
import com.jakewharton.rxbinding2.view.RxView;
import com.smarthealthring.mm.widgets.CustomDialog;
import com.smarthealthring.mm.widgets.RoundImageView;
import com.smarthealthring.mm.widgets.SingleItemView;
import com.smarthealthring.mm.widgets.photopicker.PhotoPicker;
import com.smarthealthring.mm.widgets.photopicker.utils.ImageCaptureManager;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import top.zibin.luban.Luban;

/**
 * 个人设置界面
 */
public class PersonInfoActivity extends BaseActivity<PersonalPresenter> implements PersonalContract.View {
    @BindView(R.id.tv_next)
    TextView mTvNext;
    @BindView(R.id.siv_nickname)
    SingleItemView mSivNickName;
    @BindView(R.id.siv_sex)
    SingleItemView mSivSex;
    @BindView(R.id.siv_birthday)
    SingleItemView mSivBirthday;
    @BindView(R.id.siv_weight)  //体重
            SingleItemView mSivWeight;
    @BindView(R.id.siv_height)  //身高
            SingleItemView mSivHeight;
    @BindView(R.id.rl_add_avatar) //头像
            RelativeLayout mRlAddAvatar;
    @BindView(R.id.iv_icon)
    RoundImageView mRoundIv;
    @BindView(R.id.app_img_back)
    AppCompatImageView appImgBack;

    private OptionsPickerView sexPicker;
    private TimePickerView timePicker;
    private OptionsPickerView weightPicker;
    private OptionsPickerView heightPicker;

    public ArrayList<String> selectedPhotos = new ArrayList<>();
    private ImageCaptureManager captureManager;


    @Override
    protected void initComToolBar() {
//        ComToolBar.setTitle(mContext,"修改个人信息");
//        ImageView ivLeft = ComToolBar.setleftImg(mContext, R.drawable.back_white);
//        RxView.clicks(ivLeft)
//                .subscribe((Consumer) o -> finish());
    }

    @Override
    protected int getLayout() {
        return R.layout.act_personal_set;
    }

    @Override
    protected void initEventAndData(@Nullable Bundle savedInstanceState) {
        RxView.clicks(mTvNext)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.updateInfo(new HashMap<String, String>() {{
                            put("trans_id", "2003");
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("nickname", mSivNickName.getRightText());
                            if("男".equals(mSivSex.getRightText())){
                                put("sex", "1");
                            }else if("女".equals(mSivSex.getRightText())){
                                put("sex", "2");
                            }
                            put("borndate", mSivBirthday.getRightText());
                            put("pheight", mSivHeight.getRightText());
                            put("pweight", mSivWeight.getRightText());
                            if (selectedPhotos.size() >= 1) {
                                List<File> files = Luban.with(mContext)
                                        .load(selectedPhotos)
                                        .ignoreBy(30)
                                        .get();
                                put("photo", Base64Util.imageToBase64(files.get(0).getPath()));
                                Log.e("base64===",Base64Util.imageToBase64(files.get(0).getPath()));
                            }
                            put("username", SPUtils.getString(SPUtils.USERNAME, ""));
                            put("token", SPUtils.getString(SPUtils.TOKEN, ""));
                        }});
                    }
                });

        //输入姓名
        RxView.clicks(mSivNickName)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        final EditText et = new EditText(mContext);
                        new AlertDialog.Builder(mContext).setTitle("请输入用户名")
                                .setView(et)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        //按下确定键后的事件
                                        mSivNickName.setmTvRight(et.getText().toString());
                                        Toast.makeText(getApplicationContext(), et.getText().toString(),Toast.LENGTH_LONG).show();
                                    }
                                }).setNegativeButton("取消",null).show();
                    }
                });

        //选择性别
        initSexPicker();
        RxView.clicks(mSivSex)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        sexPicker.show();
                    }
                });

        //选择生日
        initTimePicker();
        RxView.clicks(mSivBirthday)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        timePicker.show();
                    }
                });

        //选择体重
        initWeightPicker();
        RxView.clicks(mSivWeight)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        weightPicker.show();
                    }
                });

        //选择身高
        initHeightPicker();
        RxView.clicks(mSivHeight)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        heightPicker.show();
                    }
                });

        RxView.clicks(mRlAddAvatar)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        PhotoPicker.builder()
                                .setPhotoCount(1)
                                .setShowCamera(false)
                                .setPreviewEnabled(true)
                                .setSelected(selectedPhotos)
                                .setSelectedCount(selectedPhotos.size())
                                .setShowCamera(true)
                                .start(mContext);
                    }
                });

        RxBus.getInstance().tObservable(FinishHomeEvent.class)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Consumer<FinishHomeEvent>() {
                    @Override
                    public void accept(FinishHomeEvent finishHomeEvent) throws Exception {
                        finish();
                    }
                });

        appImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        setDefaultData();
    }

    private void setDefaultData(){
        mSivNickName.setmTvRight(SPUtils.getString(SPUtils.USER_NICK_NAME,""));
        if("1".equals(SPUtils.getString(SPUtils.USER_SEX,""))){
            mSivSex.setmTvRight("男");
        }else if("2".equals(SPUtils.getString(SPUtils.USER_SEX,""))){
            mSivSex.setmTvRight("女");
        }
        mSivBirthday.setmTvRight(SPUtils.getString(SPUtils.USER_BIRTH,""));
        mSivHeight.setmTvRight(SPUtils.getString(SPUtils.USER_HEIGHT,""));
        mSivWeight.setmTvRight(SPUtils.getString(SPUtils.USER_WEIGHT,""));
        GlideApp.with(mContext).load(SPUtils.getString(SPUtils.USER_PHOTO_URL,"")).into(mRoundIv);
    }

    @Override
    protected PersonalPresenter createPresenter() {
        return new PersonalPresenter();
    }

    @Override
    public void updateSuccess(UpdateInfoRes res) {
        Log.e("res==",res.getSex()+"--"+res.getBorndate()+"--"+res.getNickname()+"--"+res.getPheight()+"--"+res.getPweight());
        SPUtils.setString(SPUtils.USER_NICK_NAME,res.getNickname());
        SPUtils.setString(SPUtils.USER_SEX,res.getSex()+"");
        SPUtils.setString(SPUtils.USER_BIRTH,res.getBorndate()+"");
        SPUtils.setString(SPUtils.USER_HEIGHT,res.getPheight());
        SPUtils.setString(SPUtils.USER_WEIGHT,res.getPweight());
        SPUtils.setString(SPUtils.USER_PHOTO_URL,res.getPhotourl());
        startActivity(new Intent(PersonInfoActivity.this, HomeActivity.class));
    }

    @Override
    public void updateFail() {

    }

    /**
     * 性别选择器
     */
    private void initSexPicker() {
        List<String> sexList = new ArrayList() {{
            add("男");
            add("女");
        }};

        sexPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = sexList.get(options1);
                mSivSex.setmTvRight(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvAdd = (TextView) v.findViewById(R.id.tv_add);

                        tvAdd.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                sexPicker.returnData();
                                sexPicker.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .build();

        sexPicker.setPicker(sexList);//添加数据
    }

    /**
     * 日期选择器
     */
    private void initTimePicker() {//Dialog 模式下，在底部弹出
        timePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //返回的分别是三个级别的选中位置
                String tx = getTime(date);
                mSivBirthday.setmTvRight(tx);
            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true)
                .build();

        Dialog mDialog = timePicker.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            timePicker.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * 身高选择器
     */
    private void initHeightPicker() {
        List<String> heightList = new ArrayList();
        for (int i = 150; i < 200; i++) {
            heightList.add(i + "cm");
        }
        heightPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String str = heightList.get(options1);
                mSivHeight.setmTvRight(str);
            }
        })
                .build();
        heightPicker.setPicker(heightList);
    }

    /**
     * 体重选择器
     */
    private void initWeightPicker() {
        List<String> weightList = new ArrayList();
        for (int i = 50; i < 150; i++) {
            weightList.add(i + "kg");
        }
        weightPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String str = weightList.get(options1);
                mSivWeight.setmTvRight(str);
            }
        })
                .build();
        weightPicker.setPicker(weightList);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择照片
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                ArrayList<String> photoIds = data.getStringArrayListExtra(PhotoPicker.KEY_ONLINE_PICIDS);
                selectedPhotos = photos;                   //本地图片
            }
            GlideApp.with(mContext).load(selectedPhotos.get(0)).into(mRoundIv);
        }

        //拍照
        if (requestCode == ImageCaptureManager.REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {

            if (captureManager == null) {
                captureManager = new ImageCaptureManager(mContext);
            }

            captureManager.galleryAddPic();

            String path = captureManager.getCurrentPhotoPath();
            selectedPhotos.add(path);

            GlideApp.with(mContext).load(selectedPhotos.get(0)).into(mRoundIv);
        }
    }
}
